package com.ikangtai.shecare.personal;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.NickNameMsg;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;

public class NickNameActivity extends BaseActivity implements View.OnClickListener {

    private Button cancelBtn;
    private EditText nick_name_edit;
    private String nickName;
    private DBManager dbManager;

    private static final int SAVE_NICK_NAME_OK = 1;
    private static final int SAVE_NICK_NAME_NOK = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_nick_name);
        EventBus.getDefault().register(this);
        initView();
    }

    private void initView() {
        cancelBtn = (Button) findViewById(R.id.cancel);
        cancelBtn.setOnClickListener(this);
        nick_name_edit = (EditText) findViewById(R.id.nick_name_edit);
        nick_name_edit.setText(App.memory_preference_nickName);

        if(App.memory_preference_nickName != null && !App.memory_preference_nickName.equals("")) {
            int index = App.memory_preference_nickName.length();
            nick_name_edit.setSelection(index);
        }

        findViewById(R.id.save).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.save:

                nickName = nick_name_edit.getText().toString().trim();
                if (nickName.length() > 9) {
                    Toast.makeText(this, R.string.name_long, Toast.LENGTH_SHORT).show();
                } else if (nickName.length() == 0) {
                    Toast.makeText(this, R.string.name_null, Toast.LENGTH_SHORT).show();
                } else {
                    saveNickNme(nickName);
                }
                break;
        }
    }


    private void saveNickNme(final String userNickName) {
        AppLog.i("save nickName! userNickName = " + userNickName);
        dbManager = new DBManager(this);
        OKHttpUtil okHttpClient = new OKHttpUtil(this);

        String appendUrl = "user/modifyNickName.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("nickName", userNickName);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {
                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    sendResp(userNickName, 0);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            AppLog.i("save nickName onResponse success!");
                            sendResp(userNickName, 1);
                        } else if (App.HTTP_RESP_TOKEN_TIME_OUT == respCode) {
                            OKHttpUtil.setNewToken();
                            saveNickNme(userNickName);
                        } else {
                            AppLog.i("save nickName onResponse failed! respCode is:" + respCode);
                            sendResp(userNickName, 0);
                        }
                    } catch (JSONException e) {
                        AppLog.i("save nickName onResponse failed!");
                        e.printStackTrace();

                        sendResp(userNickName, 0);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("save nickName JSONException!");
            e.printStackTrace();

            sendResp(userNickName, 0);
        }
    }

    private void sendResp(String nickName, int isSynced) {
        NickNameMsg nickNameMsg = new NickNameMsg();

        nickNameMsg.setNickName(nickName);

        int state = (isSynced == 1 ? SAVE_NICK_NAME_OK : SAVE_NICK_NAME_NOK);
        nickNameMsg.setRespCode(state);

        EventBus.getDefault().post(nickNameMsg);
    }

    @Subcriber
    private void getNickNameEventBusMsg(NickNameMsg nickNameMsg) {
        int eventBusCode = nickNameMsg.getRespCode();
        switch (eventBusCode) {
            case SAVE_NICK_NAME_OK:
                dbManager.updateUserPreference(App.userName, "nickName", nickNameMsg.getNickName(), "isNickNameSynced", 1);
                break;
            case SAVE_NICK_NAME_NOK:
                dbManager.updateUserPreference(App.userName, "nickName", nickNameMsg.getNickName(), "isNickNameSynced", 0);
                break;
        }

        Toast.makeText(getApplicationContext(), R.string.name_success, Toast.LENGTH_SHORT).show();
        finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
